﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class TestAndroidRecord : MonoBehaviour
{
	public Text tips;
	private AudioClip clip;
	public AudioSource source;
	private string filePath = "";
	// Use this for initialization
	void Start()
	{
		//if (curAudioSource != null) return curAudioSource;
		//curAudioSource = gameObject.GetComponent<AudioSource>();
		//if (curAudioSource == null)
		//{
		//	curAudioSource = gameObject.AddComponent<AudioSource>();
		//	curAudioSource.playOnAwake = false;
		//	curAudioSource.maxDistance = 1.1f;
		//}
		//return curAudioSource;

		source = this.GetComponent<AudioSource>();
		if (source == null)
		{
			source = gameObject.AddComponent<AudioSource>();
		}
		source.playOnAwake = false;
		source.volume = 1f;
		tips.text = "AudioSource:" + source.name.ToString();
		filePath = Application.persistentDataPath + "/audiorecordtest.MP3";
	}

	void OnGUI()  
	{
		if (GUI.Button(new Rect(10, 100, 200, 60), "开始录音"))
		{
			
			tips.text = "unity:开始录音,fullName:" + filePath;
			AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
			AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
			jo.Call("StartRecord", filePath);
		}

		if (GUI.Button(new Rect(10, 200, 200, 60), "停止录音"))
		{
			AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
			AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
			jo.Call("StopRecord");
		}


		if (GUI.Button(new Rect(10, 300, 200, 60), "播放"))
		{
			AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
			AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
			jo.Call("PlayVoice");
		} 
		
		if (GUI.Button(new Rect(10, 400, 200, 60), "暂停"))
		{
			AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
			AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
			jo.Call("PauseVoice");
		}

		if (GUI.Button(new Rect(10, 500, 200, 60), "播放WWW加载音频"))
		{
			if (source)
			{
				StartCoroutine(LoadVoicFile());
			}
			else
				tips.text = "source is null";
		}

		if (GUI.Button(new Rect(10, 600, 200, 60), "播放WWW加载mp3"))
		{
			if (source)
			{
				PlayLocalFile(filePath);
			}
			else
				tips.text = "source is null";
		}

		if (GUI.Button(new Rect(10, 700, 200, 60), "播放WWW加载ogg"))
		{
			StartCoroutine(LoadOggFile());
		}

		if (Input.GetKeyDown(KeyCode.Escape))
			Application.Quit();
	}

	public void OnCoderReturn(string state)
	{
		tips.text += state;
	}

	/// <summary>
	/// 录音结束后上传音频文件
	/// </summary>
	/// <param name="path"></param>
	public void UpLoadToServer(string path)
	{
		tips.text = "安卓返回音频文件路径："+path;
	}

	/// <summary>
	/// 加载录音文件
	/// </summary>
	/// <param name="filePath"></param>
	/// <returns></returns>
	IEnumerator LoadVoicFile()
	{
		tips.text += "开始WWW加载本地音频文件："+filePath;
		string url = "file://" + filePath;
		tips.text += url;
		
		WWW www = new WWW(url);
		yield return www;
		if (www != null)
		{
			if (www.error != null)
			{
				tips.text = www.error;
				tips.text += "音频加载错误...";
			}
			else
			{
				clip = www.audioClip;
				tips.text += "length:" + clip.length;
				source.clip = clip;
				source.Play();
				tips.text += "play ok";
			}
		}
	}


	IEnumerator LoadAudio(string filePath, Action<AudioClip> loadFinish)
	{
		//安卓和PC上的文件路径
		filePath = "file://" + filePath;
		tips.text = string.Format("local audioclip :{0}", filePath);
		WWW www = new WWW(filePath);
		yield return www;

		if (string.IsNullOrEmpty(www.error))
		{
			AudioClip audioClip = null;
			//OGG文件会报：Streaming of 'ogg' on this platform is not supported
			//if (filePath.EndsWith("ogg"))
			//{
			//    audioClip = www.GetAudioClip(false, true, AudioType.OGGVORBIS);
			//}
			//else
			{
				audioClip = www.audioClip;
			}
			loadFinish(audioClip);
		}
		else
		{
			tips.text += string.Format("www load file error:{0}", www.error);
		}
	}
	void PlayLocalFile(string audioPath)
	{
		var exists = File.Exists(audioPath);
		tips.text += string.Format("{0}，存在:{1}", audioPath, exists);
		StartCoroutine(LoadAudio(audioPath, (audioClip) =>
		{
			source.clip = audioClip;
			tips.text = source.clip.length.ToString();
			source.Play();
		}));
	}

	public IEnumerator LoadOggFile()
	{
		string url = "file://" + filePath;
		WWW data = new WWW(url); 
		yield return data;
		AudioClip ac = data.GetAudioClipCompressed(false, AudioType.MPEG) as AudioClip;
		if (ac != null)
		{
			ac.name = "mySoundFile.ogg";
			gameObject.GetComponent<AudioSource>().clip = ac;
			gameObject.GetComponent<AudioSource>().Play();
		}
		else
		{
			gameObject.GetComponent<AudioSource>().clip = null;
			tips.text = "no audio found.";
		}
	}
}
